package com.huawei.fastble;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleIndicateCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleReadCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.TextTool;
import ohos.bluetooth.ble.GattCharacteristic;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

public class CharacteristicOperationAbility extends Ability implements Component.ClickedListener {
    GattCharacteristic characteristic;
    Button btnRead;
    Button btnWrite;
    Button btnWriteNoResponse;
    Button btnNotify;
    Button btnIndicate;
    Text txtInfo;
    Text txt_uuid;
    Text txt_properties;
    BleDevice bleDevice;
    TextField tfWrite;
    TextField tfWriteNo;
    DirectionalLayout dr_write;
    DirectionalLayout dr_write_no_re;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_characteristic_operation);
        String properties = intent.getStringParam("properties").trim();
        characteristic = FastBleMyApplication.getGattCharacteristic();
        if (characteristic == null) {
            return;
        }

        bleDevice = FastBleMyApplication.getBleDevice();
        txtInfo = (Text) findComponentById(ResourceTable.Id_txt_info);
        btnRead = (Button) findComponentById(ResourceTable.Id_btn_read);
        btnWrite = (Button) findComponentById(ResourceTable.Id_btn_write);
        btnWriteNoResponse = (Button) findComponentById(ResourceTable.Id_btn_write_no_response);
        btnNotify = (Button) findComponentById(ResourceTable.Id_btn_notify);
        btnIndicate = (Button) findComponentById(ResourceTable.Id_btn_indicate);
        tfWrite = (TextField) findComponentById(ResourceTable.Id_tf_write);
        tfWriteNo = (TextField) findComponentById(ResourceTable.Id_tf_write_no);
        txt_properties = (Text) findComponentById(ResourceTable.Id_txt_properties);
        txt_uuid = (Text) findComponentById(ResourceTable.Id_txt_uuid_title);
        dr_write = (DirectionalLayout) findComponentById(ResourceTable.Id_dr_write);
        dr_write_no_re = (DirectionalLayout) findComponentById(ResourceTable.Id_dr_write_no_re);

        btnRead.setClickedListener(this);
        btnWrite.setClickedListener(this);
        btnWriteNoResponse.setClickedListener(this);

        txt_uuid.setText("UUID:" + characteristic.getUuid().toString());
        txt_properties.setText("properties：" + properties);

        if (properties.contains("Read") || properties.contains("Read,")) {
            btnRead.setVisibility(Component.VISIBLE);
        }

        if (properties.contains("Write") || properties.contains("Write,")) {
            dr_write.setVisibility(Component.VISIBLE);
        }

        if (properties.contains("Write No Response") || properties.contains("Write No Response,")) {
            dr_write_no_re.setVisibility(Component.VISIBLE);
        }
    }

    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_btn_read) {
            BleManager.getInstance()
                    .read(
                            bleDevice,
                            characteristic.getService().getUuid().toString(),
                            characteristic.getUuid().toString(),
                            new BleReadCallback() {
                                @Override
                                public void onReadSuccess(final byte[] data) {
                                    setInfo(HexUtil.formatHexString(data, true));
                                }

                                @Override
                                public void onReadFailure(final BleException exception) {
                                    setInfo(exception.toString());
                                }
                            });
        } else if (component.getId() == ResourceTable.Id_btn_write) {
            String hex = tfWrite.getText();
            if (TextTool.isNullOrEmpty(hex)) {
                return;
            }
            BleManager.getInstance()
                    .write(
                            bleDevice,
                            characteristic.getService().getUuid().toString(),
                            characteristic.getUuid().toString(),
                            HexUtil.hexStringToBytes(hex),
                            new BleWriteCallback() {
                                @Override
                                public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                    setInfo(
                                            "write success, current: "
                                                    + current
                                                    + " total: "
                                                    + total
                                                    + " justWrite: "
                                                    + HexUtil.formatHexString(justWrite, true));
                                }

                                @Override
                                public void onWriteFailure(final BleException exception) {
                                    setInfo(exception.toString());
                                }
                            });
        } else if (component.getId() == ResourceTable.Id_btn_write_no_response) {
            String hex = tfWriteNo.getText();
            if (TextTool.isNullOrEmpty(hex)) {
                return;
            }
            BleManager.getInstance()
                    .write(
                            bleDevice,
                            characteristic.getService().getUuid().toString(),
                            characteristic.getUuid().toString(),
                            HexUtil.hexStringToBytes(hex),
                            new BleWriteCallback() {
                                @Override
                                public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                    setInfo(
                                            "write success, current: "
                                                    + current
                                                    + " total: "
                                                    + total
                                                    + " justWrite: "
                                                    + HexUtil.formatHexString(justWrite, true));
                                }

                                @Override
                                public void onWriteFailure(final BleException exception) {
                                    setInfo(exception.toString());
                                }
                            });
        } else if (component.getId() == ResourceTable.Id_btn_notify) {
            BleManager.getInstance()
                    .notify(
                            bleDevice,
                            characteristic.getService().getUuid().toString(),
                            characteristic.getUuid().toString(),
                            new BleNotifyCallback() {
                                @Override
                                public void onNotifySuccess() {
                                    setInfo("notify success");
                                }

                                @Override
                                public void onNotifyFailure(final BleException exception) {
                                    setInfo(exception.toString());
                                }

                                @Override
                                public void onCharacteristicChanged(byte[] data) {
                                    setInfo(HexUtil.formatHexString(characteristic.getValue(), true));
                                }
                            });
        } else if (component.getId() == ResourceTable.Id_btn_indicate) {
            BleManager.getInstance()
                    .indicate(
                            bleDevice,
                            characteristic.getService().getUuid().toString(),
                            characteristic.getUuid().toString(),
                            new BleIndicateCallback() {
                                @Override
                                public void onIndicateSuccess() {
                                    setInfo("indicate success");
                                }

                                @Override
                                public void onIndicateFailure(final BleException exception) {
                                    setInfo(exception.toString());
                                }

                                @Override
                                public void onCharacteristicChanged(byte[] data) {
                                    setInfo(HexUtil.formatHexString(characteristic.getValue(), true));
                                }
                            });
        }
    }

    /**
     * setInfo
     * @param info info
     */
    public void setInfo(String info) {
        new EventHandler(EventRunner.getMainEventRunner())
                .postTask(
                        new Runnable() {
                            @Override
                            public void run() {
                                txtInfo.setText(info);
                            }
                        });
    }
}
